from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from app import db
from app.models import User, Role
from app.utils.decorators import admin_required
import re

users_bp = Blueprint('users', __name__)

@users_bp.route('/', methods=['GET'])
@jwt_required()
@admin_required
def get_users():
    """获取用户列表"""
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)
    search = request.args.get('search', '')
    
    query = User.query
    
    if search:
        query = query.filter(
            db.or_(
                User.username.contains(search),
                User.email.contains(search),
                User.real_name.contains(search)
            )
        )
    
    pagination = query.paginate(
        page=page, per_page=per_page, error_out=False
    )
    
    users = pagination.items
    
    return jsonify({
        'users': [user.to_dict() for user in users],
        'pagination': {
            'page': page,
            'per_page': per_page,
            'total': pagination.total,
            'pages': pagination.pages
        }
    }), 200

@users_bp.route('/<int:user_id>', methods=['GET'])
@jwt_required()
@admin_required
def get_user(user_id):
    """获取用户详情"""
    user = User.query.get(user_id)
    
    if not user:
        return jsonify({'message': '用户不存在'}), 404
    
    return jsonify({'user': user.to_dict()}), 200

@users_bp.route('/', methods=['POST'])
@jwt_required()
@admin_required
def create_user():
    """创建用户"""
    data = request.get_json()
    
    if not data:
        return jsonify({'message': '请求数据不能为空'}), 400
    
    username = data.get('username')
    email = data.get('email')
    password = data.get('password')
    real_name = data.get('real_name', '')
    phone = data.get('phone', '')
    
    if not username or not email or not password:
        return jsonify({'message': '用户名、邮箱和密码不能为空'}), 400
    
    # 验证用户名格式
    if re.match(r'^[a-zA-Z0-9_]{3,20}$', username) is None:
        return jsonify({'message': '用户名格式不正确'}), 400
    
    # 验证邮箱格式
    if re.match(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$', email) is None:
        return jsonify({'message': '邮箱格式不正确'}), 400
    
    # 验证密码长度
    if len(password) < 6:
        return jsonify({'message': '密码长度不能少于6位'}), 400
    
    # 检查用户名是否已存在
    if User.query.filter_by(username=username).first():
        return jsonify({'message': '用户名已存在'}), 400
    
    # 检查邮箱是否已存在
    if User.query.filter_by(email=email).first():
        return jsonify({'message': '邮箱已存在'}), 400
    
    user = User(
        username=username,
        email=email,
        real_name=real_name,
        phone=phone
    )
    user.password = password
    
    # 分配角色
    role_ids = data.get('role_ids', [])
    if role_ids:
        roles = Role.query.filter(Role.id.in_(role_ids)).all()
        user.roles = roles
    
    try:
        db.session.add(user)
        db.session.commit()
        return jsonify({
            'message': '用户创建成功',
            'user': user.to_dict()
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': '用户创建失败'}), 500

@users_bp.route('/<int:user_id>', methods=['PUT'])
@jwt_required()
@admin_required
def update_user(user_id):
    """更新用户"""
    user = User.query.get(user_id)
    
    if not user:
        return jsonify({'message': '用户不存在'}), 404
    
    data = request.get_json()
    
    if not data:
        return jsonify({'message': '请求数据不能为空'}), 400
    
    # 允许更新的字段
    allowed_fields = ['real_name', 'email', 'phone', 'avatar', 'is_active']
    
    for field in allowed_fields:
        if field in data:
            setattr(user, field, data[field])
    
    # 更新角色
    if 'role_ids' in data:
        role_ids = data['role_ids']
        roles = Role.query.filter(Role.id.in_(role_ids)).all()
        user.roles = roles
    
    try:
        db.session.commit()
        return jsonify({
            'message': '用户更新成功',
            'user': user.to_dict()
        }), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': '用户更新失败'}), 500

@users_bp.route('/<int:user_id>', methods=['DELETE'])
@jwt_required()
@admin_required
def delete_user(user_id):
    """删除用户"""
    user = User.query.get(user_id)
    
    if not user:
        return jsonify({'message': '用户不存在'}), 404
    
    if user.is_superuser:
        return jsonify({'message': '不能删除超级管理员'}), 400
    
    try:
        db.session.delete(user)
        db.session.commit()
        return jsonify({'message': '用户删除成功'}), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': '用户删除失败'}), 500

@users_bp.route('/<int:user_id>/reset-password', methods=['POST'])
@jwt_required()
@admin_required
def reset_user_password(user_id):
    """重置用户密码"""
    user = User.query.get(user_id)
    
    if not user:
        return jsonify({'message': '用户不存在'}), 404
    
    data = request.get_json()
    new_password = data.get('new_password', '123456')
    
    if len(new_password) < 6:
        return jsonify({'message': '密码长度不能少于6位'}), 400
    
    user.password = new_password
    
    try:
        db.session.commit()
        return jsonify({'message': '密码重置成功'}), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': '密码重置失败'}), 500 